from . import passport_blue
from flask import request,jsonify,current_app,make_response,session
# 导入自定义状态码
from info.utils.response_code import RET
from info.utils.captcha.captcha import captcha
from info import redis_score,constants,db
import re,random
from info.libs.yuntongxun import sms
# 导入模型类
from info.models import User
from datetime import datetime

@passport_blue.route('/image_code')
def generate_image_code():

    image_code_id = request.args.get('image_code_id')
    if not image_code_id:
        return jsonify(errno=RET.PARAMERR,errmsg='参数缺失')
    name,text,image = captcha.generate_captcha()

    try:
        redis_score.setex('ImageCode_' + image_code_id,constants.IMAGE_CODE_REDIS_EXPIRES,text)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='保存图片验证码失败')
    else:
        response = make_response(image)
        response.headers['Content-Type'] = 'image/jpg'
        return response

@passport_blue.route('/sms_code',methods=['POST'])
def send_sms_code():
    # 发送短信
    mobile = request.json.get('mobile')
    image_code = request.json.get('image_code')
    image_code_id = request.json.get('image_code_id')
    if not all([mobile,image_code,image_code_id]):
        return jsonify(errno=RET.PARAMERR,errmsg='参数缺失')
    if not re.match(r'1[3456789]\d{9}$',mobile):
        return jsonify(errno=RET.PARAMERR, errmsg='手机号格式错误')
    try:
        real_image_code = redis_score.get('ImageCode_' + image_code_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='查询数据失败')
    if not real_image_code:
        return jsonify(errno=RET.NODATA,errmsg='数据已过期')
    try:
        redis_score.delete('Image_Code_' + image_code_id)
    except Exception as e:
        current_app.logger.error(e)
    if real_image_code.lower() != image_code.lower():
        return jsonify(errno=RET.DATAERR,errmsg='图片验证不一致')

    # 根据手机号查询数据库，确认用户未注册，如果用户未注册，才发送短信
    try:
        user = User.query.filter(User.mobile == mobile).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询用户数据失败')
    else:
        # 如果用户已存在
        if user:
            return jsonify(errno=RET.DATAEXIST, errmsg='手机号已注册')

    # 生成六位数的短信验证码
    sms_code = '%06d' % random.randint(0, 999999)
    print(sms_code)
    try:
        redis_score.setex('SMSCode_' + mobile,constants.SMS_CODE_REDIS_EXPIRES,sms_code)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='保存数据失败')
    try:
        cpp = sms.CCP()
        result = cpp.send_template_sms(mobile,[sms_code,constants.SMS_CODE_REDIS_EXPIRES/60],1)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR,errmsg='发送短信异常')
    if result == 0:
        return jsonify(errno=RET.OK, errmsg='发送成功')
    else:
        return jsonify(errno=RET.THIRDERR, errmsg='发送失败')

@passport_blue.route('/register',methods=['POST'])
def register():
    """
    获取参数-检查参数-业务处理-返回结果
    :return:
    """
    # 获取参数
    mobile =  request.json.get('mobile')
    sms_code = request.json.get('sms_code')
    password = request.json.get('password')
    # 检查参数完整性
    if not all([mobile,sms_code,password]):
        return jsonify(errno=RET.PARAMERR,errmsg='参数不完整')
    # 检查手机号格式
    if not re.match(r'1[3456789]\d{9}$',mobile):
        return jsonify(errno=RET.PARAMERR, errmsg='手机号格式错误')
    # 从redis数据库中获取真实的短信验证码
    try:
        real_sms_code = redis_score.get('SMSCode_' + mobile)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='获取短信验证码失败')
    # 判断获取结果
    if not real_sms_code:
        return jsonify(errno=RET.NODATA,errmsg='短信验证码已过期')
    # 比较短信验证码是否正确
    if real_sms_code != str(sms_code):
        return jsonify(errno=RET.DATAERR,errmsg='验证码不一致')
    # 删除redis中存在的短信验证码
    try:
        redis_score.delete('SMSCode_' + mobile)
    except Exception as e:
        current_app.logger.error(e)
    # 根据手机号查询数据库确认用户未注册
    try:
        user = User.query.filter(User.mobile==mobile).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='查询用户数据失败')
    else:
        if user:
            return jsonify(errno=RET.DATAERR,errmsg='手机号已注册')
    # 保存用户数据
    user = User()
    user.nick_name = mobile
    user.mobile = mobile
    user.password = password
    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        # 若提交数据失败，进行回滚
        db.session.rollback()
        return jsonify(errno=RET.DBERR,errmsg='保存用户数据失败')
    # 缓存用户信息到redis数据库
    session['user_id'] = user.id
    session['nick_name'] = mobile
    session['mobile'] = mobile
    return jsonify(errno=RET.OK,errmsg='OK')

@passport_blue.route('/login',methods=['POST'])
def login():
    mobile = request.json.get('mobile')
    password = request.json.get('password')
    # 检查参数完整性
    if not all([mobile, password]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数缺失')
    # 检查手机号格式
    if not re.match(r'1[3456789]\d{9}$', mobile):
        return jsonify(errno=RET.PARAMERR, errmsg='手机号格式错误')
    # 根据手机号查询mysql，确认用户已注册
    try:
        user = User.query.filter_by(mobile=mobile).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询用户数据失败')
    # if not user:
    #     return jsonify(errno=RET.NODATA,errmsg='用户未注册')
    # import hashlib
    # hashlib.sha256
    # 判断密码是否正确
    # if not user.check_password(password):
    #     return jsonify(errno=RET.PWDERR,errmsg='密码错误')

    # 判断用户不存在，密码是错误的
    if user is None or not user.check_password(password):
        return jsonify(errno=RET.DATAERR, errmsg='用户名或密码错误')
    # 保存用户登陆时间
    user.last_login = datetime.now()
    # 提交数据到mysql
    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR,errmsg='保存用户数据失败')
    # 缓存用户信息
    session['user_id'] = user.id
    session['nick_name'] = user.nick_name
    session['mobile'] = user.mobile
    return jsonify(errno=RET.OK, errmsg='OK')

@passport_blue.route('/logout')
def logout():
    session.pop('user_id',None)
    session.pop('nick_name',None)
    session.pop('mobile',None)
    return jsonify(errno=RET.OK,errmsg='OK')

